const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

onerror(app)
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/upload'))
app.use(require('./middleware/init'))

app.use(async (ctx, next) => {
  console.log(ctx.url)
  if (ctx.url.match(/^\/test/)) {
    ctx.json({
      apiName: '/test',
      get: ctx.get,
      post: ctx.post,
    })
  } else {
    await next()
  }
})

app.use(async (ctx, next) => {
  console.log(ctx.user)
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error:', err, ctx)
});

module.exports = app
